import * as API_NetworkAuth from '../../../api/networkAuth'
import * as API_Article from '../../../api/article'
import * as API_Passport from '../../../api/passport'
let WxParse = require('../../../lib/wxParse/wxParse')
Page({
  data:{
    registerForm:{
      mobile:'',
      invitationCode:'',
      code:'',
    },
    uuid:'',
    initTip: '发送验证码',
    endTip: '重新获取',
    sufTip: '秒后重新获取',
    count_time: 60,
    disabled: false,
    interval:null,
    message: '',
    showAgreement: false,//是否显示注册协议
    agreement: '', // 注册协议
    agreed: false, // 同意注册协议
    agreementCb:true
  },
  onLoad: function (options) {
    const uuid = wx.getStorageSync('uuid')
    let qrId=wx.getStorageSync('qrId')
    let inviteCode = wx.getStorageSync('inviteCode')
    this.setData({ uuid: uuid })
    if(inviteCode){
      this.setData({ "registerForm.invitationCode": inviteCode })
    }
    if(qrId){
      this.setData({"registerForm.invitationCode": qrId})
    }
    /* 分享进入  填入推荐人*/
    if (options.su) {
      this.setData({ su: options.su })
      API_NetworkAuth.accessShortLink({ su: options.su, uuid: wx.getStorageSync('uuid') }).then(res => {
        this.setData({ "registerForm.invitationCode": res.mobile, isReferrerMobile: true })
      })
    }

    this.loadPage();
  },
  // 表单双向绑定
  syncMobile(e){this.setData({ "registerForm.mobile": e.detail.value })},
  syncInvitationCode(e){this.setData({ "registerForm.invitationCode": e.detail.value })},
  // syncCode(e){this.setData({ "form.code": e.detail.value })},

  //下一步
  handleNextStep() {

    const { mobile, invitationCode } = this.data.registerForm
    if (!mobile) {
      wx.showToast({ title: '请输入手机号！', icon: 'none' })
      return false
    }
    this.handleConfirmRegister();
  },
  //立即注册
  handleConfirmRegister() {
    const { mobile, invitationCode/*,  password, rep_password */ } = this.data.registerForm
    API_Passport.checkMobileRepeat(mobile).then(response=>{
      //手机号未注册
      if(!response.exist){
    // 获取用户信息
    wx.getUserInfo({
      lang: 'zh_CN',
      success: (res) => {
        const userInfo = res.userInfo
        //输入邀请码
        if(this.data.registerForm.invitationCode){
          //检测邀请码
          API_Passport.checkMobileRepeat(this.data.registerForm.invitationCode).then(res=>{
            //邀请码不存在
            if(!res.exist){
              wx.showToast({
                title: '邀请码不存在！',
                icon: 'none'

              })
            }
            //邀请码存在
            else{
              const params = {
                nick_name: userInfo.nickName,
                face: userInfo.avatarUrl,
                sex: userInfo.gender === 1 ? 1 : 0,
                mobile: mobile,
                password: '000000',
                referrer_mobile:this.data.registerForm.invitationCode
              }
              // 注册绑定
              API_NetworkAuth.registerBindConnect(this.data.uuid, params).then((res) => {
                const { access_token, refresh_token, uid } = res
                wx.setStorageSync('access_token', access_token)
                wx.setStorageSync('refresh_token', refresh_token)
                wx.setStorageSync('uid', uid)
                this.setData({ su: null });
                API_NetworkAuth.getUserInfo().then((response) => {
                  wx.setStorageSync('user', response)
                  wx.navigateBack({
                    delta: 2
                  })
                })
              })
            }
          })
        }
        //未输入邀请码
        else{
          const params = {
            nick_name: userInfo.nickName,
            face: userInfo.avatarUrl,
            sex: userInfo.gender === 1 ? 1 : 0,
            mobile: mobile,
            password: '000000',
            referrer_mobile:''
          }
          // 注册绑定
          API_NetworkAuth.registerBindConnect(this.data.uuid, params).then((res) => {
            const { access_token, refresh_token, uid } = res
            wx.setStorageSync('access_token', access_token)
            wx.setStorageSync('refresh_token', refresh_token)
            wx.setStorageSync('uid', uid)
            this.setData({ su: null });
            API_NetworkAuth.getUserInfo().then((response) => {
              wx.setStorageSync('user', response)
              wx.navigateBack({
                delta: 2
              })
            })
          })
        }

      }
    })        
   }
      //手机号已注册
    else{
    wx.showToast({
      title: '该手机号已注册！',
      icon: 'none'
      })
  }
    })

  },
  loadPage() {
    // 如果未授权 进行授权
    // if (wx.getStorageSync('wxauth')) {
    //   this.setData({ showWxAuth: true })
    // } else {
    //   this.setData({ showWxAuth: false })
    // }
    // 获取用户协议
    API_Article.getArticleByPosition('REGISTRATION_AGREEMENT').then(response => {
      WxParse.wxParse('agreement', 'html', response.content, this)
    })
  },
  //同意协议
  handleAgreement(e) {
    const agreed = JSON.parse(e.currentTarget.dataset.agreed)
    if (!agreed) {
      wx.switchTab({ url: '/pages/home/home' })
    } else {
      this.setData({
        showAgreement: false,
        agreed: agreed
      })
    }
  },
  // 授权手机号
  getPhoneNumber(e){
    var self = this;
    // 允许后执行
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      var params = {
          encrypted_data : e.detail.encryptedData,
          iv: e.detail.iv,
          session_key : wx.getStorageSync('session_key')
      }
      wx.request({
        url: 'https://apibuyer.oupinguoji.cn/passport/mini-program/phone/decrypt',
        data: params,
        method: 'POST',
        success: function (res) {
          self.setData({
            'registerForm.mobile': res.data.phoneNumber
          })
        },
        fail: function (err) {
          console.log(err)
        }
      })
    }
  },
  // 显示注册协议
  showagreement(){
    this.setData({showAgreement:true})
  },
  // 
  toLogin(){
    wx.navigateTo({
      url: '/pages/auth/login/login',
    })
  }
})